<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<title>角色授权用户选择</title>
	<link type="text/css" rel="stylesheet" href="../<s:property value="#session.themeStyle.mainCss" default="Skin/PM/cyan/main.css"/>" />
	<link type="text/css" rel="stylesheet" href="../css/zTreeStyle/zTreeStyle.css" />
	<link type="text/css" rel="stylesheet" href="../css/jquery.loadmask.css">
	<style type="text/css">
		.trStyle td{
			text-align: center;
		}
		.buttonLab{
			cursor: pointer;
			background-image: url('../images/main/button_bg.png');
			width: 80px; 
			height: 22px;
			color:white;
		}
	</style>
</head>
<body>
	<s:form theme="simple">
	<font style="font-weight: bold;">角色</font>：<s:property value="role.name"/>
	<div style="height: 30px;margin-top: 5px;border-bottom: #3497cf 1px solid;text-align: center;"><a class="but28"  onclick="saveAndClose();" >确定</a></div>
	<div id="orgTree" >
		<ul id="ultree" class="ztree"></ul>
	</div>
	</s:form>
	<script type="text/javascript" src="../js/jquery.js"></script>
	<script type="text/javascript" src="../js/jquery.loadmask.min.js"></script>
	<script type="text/javascript" src="../js/ztree/jquery.ztree.core-3.5.js"></script>
	<script type="text/javascript" src="../js/ztree/jquery.ztree.excheck-3.5.js"></script>
	<script type="text/javascript" src="../js/modalWindow.js"></script>
	<script type="text/javascript" src="../js/store.js"></script>
	<script type="text/javascript">

		var changed = false;
	
		var setting = {
			async: {
                enable: true,
                url:"userRole-loadSubNodes.action",
				autoParam:["id"],	
                type: "post"  
            },
			check: {
				enable: true
			},
			data: {
				simpleData: {
					enable: true
				}
			},
			callback: {
				onClick: function(event, treeId, treeNode, clickFlag) {
					var deptId = treeNode.deptId;
				},
				onAsyncSuccess: function(event, treeId, treeNode, msg) {
					curAsyncCount--;
					// 当前节点是否已经处理
					var currentNodeId = $("#currentNodeId").val();
					if (currentNodeId==""){
						// 默认处理
						if (treeNode==null){
							var treeObj = $.fn.zTree.getZTreeObj(treeId);//获取ztree对象
							var currentNode = treeObj.getNodesByFilter(function (node) { return node.level == 0 }, true);
							if (currentNode!=null){
								$("#currentNodeId").val(currentNode.id);
								treeObj.selectNode(currentNode);
								onClick(event, treeId, currentNode);
								treeObj.expandNode(currentNode, true, false, false);
							}
						}				
					}else{
						// 
					}
					if(currentNode==null){
						// 未处理
						var treeObj = $.fn.zTree.getZTreeObj(treeId);
						currentNode = treeObj.getNodeByParam("id", currentNodeId);
						if (currentNode){
							treeObj.selectNode(currentNode);
							onClick(event, treeId, currentNode);
						}else{
						}
					}
					if (treeNode==null){
						var treeObj = $.fn.zTree.getZTreeObj(treeId);//获取ztree对象
						var node = treeObj.getNodesByFilter(function (node) { return node.level == 0 }, true);
						if (node!=null){
							treeObj.expandNode(node, true, false, false);
						}
					}else{
						if (curStatus == "expand") { 
							expandNodes(treeNode.children);
							alert("expand");
						} else if (curStatus == "async") { 
							asyncNodes(treeNode.children); 
							alert("async");
						}else if(curStatus == "init"){
						}else{
							
						}
					}
					
					if (curAsyncCount <= 0) { 
					  curStatus = ""; 
					}
					
				}

			}
		};
	
		$(document).ready(function(){
			var treeObj = $.fn.zTree.init($("#ultree"), setting);
			initWindow();
		});
		
		function refreshTree(){
			var zTree = $.fn.zTree.getZTreeObj("ultree");
			if (currentNode!=null){
				alert("刷新"+currentNode.name);
				zTree.reAsyncChildNodes(null, "refresh");
			}else{
				alert("刷新空！");
				zTree.reAsyncChildNodes(null, "refresh");
			} 
		}
		
		var curStatus = "init", curAsyncCount = 0, goAsync = false;
		var currentNode = null;
		
		function expandAll() { 
			if (!asyncComplate()) { 
				return; 
			} 
			var zTree = $.fn.zTree.getZTreeObj("ultree"); 
			expandNodes(zTree.getNodes()); 
			if (!goAsync) { 
				curStatus = ""; 
			}
		}
		
		function expandNodes(nodes) {
			if (!nodes) return;
			curStatus = "expand";
			var zTree = $.fn.zTree.getZTreeObj("ultree");
			for (var i=0, l=nodes.length; i<l; i++) {
				zTree.expandNode(nodes[i], true, false, false);//展开节点就会调用后台查询子节点
				if (nodes[i].isParent && nodes[i].zAsync) {
					expandNodes(nodes[i].children);//递归
				} else {
					goAsync = true;
				}
			}
		}

		function asyncComplate() {
			if (curAsyncCount > 0) {
				return false;
			}
			return true;
		}
 
		function initWindow(){
			if (window.top!=window.self){
				var height = window.parent.document.getElementById("mainFrame").height-2;
				var width = window.parent.document.getElementById("mainFrame").width-2;
				$("#divMain").height(height-50);
				$("#divMain").width(width-20);
				$("#divTree").height(height-57);
				$("#showList").height(height-57);
				$("#divTable11").height(height/2-35);
				$("#divTable22").height(height/2-35);
				if($("#divMain").width()<1110){
					$("#divMain").width(1110);
				}
			}
			$("showList").empty();
		}
		
		function deleteUserRole(userId,obj,name,roleName){
			if(confirm("确定要解除用户["+name+"]的["+roleName+"]授权？")){
				var roleId = $("#roleId").val(); 
				$.post("deleteUserRole.action", { roleId: roleId, userId: userId },
				  	function(data){
				    	$(obj).parent().parent().remove();
				});
			}
			
		}
		
		// 保存并关闭
		function saveAndClose(){
			if (changed){
			}else{
				
			}
			var zTree = $.fn.zTree.getZTreeObj("ultree");
            var nodes = zTree.getCheckedNodes(true);
            var purview = "";
            for (var i = 0; i < nodes.length; i++) {
				if(!nodes[i].getCheckStatus().half){
					if(nodes[i].userId!=undefined){
						if(purview==""){
							purview = nodes[i].userId;
						}else{
							purview += "," + nodes[i].userId;
						}
					}
				}
            }
            window.returnValue=purview;
    		window.close();
		}
		
		/**
		 * Array对象有许多基础方法，例如：push（增加），join（转化为字符串、以逗号分隔），sort（排序），但是没有提供删除方法，这里需要自己实现。
		 * @param dx
		 * @returns {Boolean}
		 */

		Array.prototype.remove = function(dx) {
			if (isNaN(dx) || dx > this.length) {
				return false;
			}
			for (var i = 0, n = 0; i < this.length; i++) {
				if (this[i] != this[dx]) {
					this[n++] = this[i]
				}
			}
			this.length -= 1

			// 需要注意，每次删除完一个数组元素，数组的长度会减1.
		}

		var roleUserList = new Array(); //权限数组

		function buildPermissionStr(obj) {
			var name = obj.name;
			var mail = name.split("=")[0];
			var perm = name.split("=")[1];

			if (obj.checked) {
				if (perm == 'S') {
					document.getElementById(mail).style.display = "";

					//根据名称得到复选框数组，清空选择
					var arr = document.getElementsByName(mail);
					for (i = 0; i < arr.length; i++) {
						arr[i].checked = false;
					}
				}
			} else {
				if (perm == 'S') {
					document.getElementById(mail).style.display = "none";

					//因为上面提供的删除方法，每次删除后，数组对象长度减一，所以这里先保存数组长度，然后，根据查找得到的元素索引，删除，这样可以保证删除完整。
					var sum = roleUserList.length;
					for (var i = 0; i < sum; i++) {
						var ex = isMailExist(mail);
						if (ex > -1)
							roleUserList.remove(ex);
					}
				}
			}

			//数组添加对象时，先判断是否包含
			var exist = isExist(name);
			
			if (obj.checked) {
				if (exist < 0) { //数组不包含元素
					roleUserList.push(name);
				}
			} else {
				if (exist >= 0) { //数组包含元素
					roleUserList.remove(exist);
				}
			}
		}

		//遍历数组，如果包含传入的字符传，返回元素索引

		function isMailExist(email) {
			var index;
			if (roleUserList.length == 0) {
				return -1;
			}
			for (var i = 0; i < roleUserList.length; i++) {
				if (roleUserList[i].indexOf(email) >= 0)
					return i;
			}

			return -1;

		}

		//遍历数组，根据字符串的值得到索引

		function isExist(emailAddr) {
			var index;
			if (roleUserList.length == 0) {
				return -1;
			}
			for (var i = 0; i < roleUserList.length; i++) {
				if (emailAddr == roleUserList[i])
					return i;
			}

			return -1;

		}

		//提交时，对于数组对象进行操作，sort为排序，join转换为字符串

		function validate(obj) {
			var sortArray = roleUserList.sort();
			var strArray = roleUserList.join();

			for (var i = 0; i < sortArray.length; i++) {
				var mail = sortArray[i].split("=")[0];
				var perm = sortArray[i].split("=")[1];

				if (perm == 'S') {
					if (strArray.indexOf(mail) < 0) {
						alert(mail + "选择了发送权限,但是没有选择白名单！");
						return false;
					}

				}
			}

			var permisions = document.getElementById("${group.permisions.key}");
			var whiteListIds = document.getElementById("${group.whiteListIds.key}");
			permisions.value = roleUserList.sort().join();

			if (permisions.value == "") {
				alert("请选择系统邮件和邮件白名单！");
				return false;
			}

			obj.style.display = "none";
			document.getElementById("hid_sub").style.display = "";

			return true;
		}
		
	</script>
</body>
</html>
